<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\api\controller;

use app\common\service\FileService;
use app\model\DiscussModel;
use app\model\MediaCheckModel;
use app\model\PostModel;
use app\model\TopicModel;
use app\model\PostCommentModel;
use app\model\PostLikeModel;
use app\model\PostCollectionModel;
use app\model\TopicClassModel;
use app\common\service\Message;
use app\common\service\WeChatMnpService;

use app\model\TopicTopModel;
use app\model\UsersModel;
use support\exception\BusinessException;

class Post extends BaseApi
{
    protected ?string $dataModel = PostModel::class;
    protected array $with = ["user","topic","discuss"];
    protected array $allowSearch = ['discuss_id', 'topic_id', 'class_id', 'topic_class_id', 'user_id'];
    protected array $searchConfig = [
        'discuss_id' => ['type' => 'exact'],
        'topic_id' => ['type' => 'exact'],
        'class_id' => ['type' => 'exact'],
        'topic_class_id' => ['type' => 'exact'],
        'user_id' => ['type' => 'exact']
    ];


    /**
     * 发布帖子
     * @return \support\Response
     */
    public function release()
    {
        try {
            // 参数验证
            $params = $this->validatePostParams();

            // 用户验证
            $user = $this->validateUser();

            // 内容安全检查
            $this->validateContentSecurity($user, $params['content']);

            // 创建帖子
            $post = $this->createPost($params, $user->id);

            // 更新统计数据
            $this->updatePostStatistics($post, $user);

            return $this->success(['id' => $post->id], '发布成功');

        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 验证帖子参数
     * @return array
     * @throws \Exception
     */
    private function validatePostParams()
    {
        $params = request()->post();

        // 基础参数验证
        $validator = validator($params, [
            'topic_id' => 'required',
            'class_id' => 'required',
            'content' => 'required|string|min:1|max:2000',
            'title' => 'nullable|string|max:100',
            'media' => 'nullable|array|max:9',
        ], [
            'topic_id.required' => '请选择发布圈子',
            'class_id.required' => '类目ID不能为空',
            'content.required' => '请输入帖子内容',
            'content.min' => '帖子内容不能为空',
            'content.max' => '帖子内容不能超过2000字',
            'title.max' => '标题不能超过100字',
            'media.array' => '媒体文件格式错误',
            'media.max' => '最多只能上传9个媒体文件'
        ]);

        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first());
        }

        // 验证圈子是否存在
        $topic = TopicModel::find($params['topic_id']);
        if (!$topic) {
            throw new \Exception('圈子不存在');
        }

        // 验证话题是否存在（如果提供了discuss_id）
        if (!empty($params['discuss_id'])) {
            $discuss = DiscussModel::find($params['discuss_id']);
            if (!$discuss) {
                throw new \Exception('话题不存在');
            }
        }

        return $params;
    }

    /**
     * 验证用户
     * @return UsersModel
     * @throws \Exception
     */
    private function validateUser()
    {
        $userId = $this->getUserId();
        $user = UsersModel::find($userId);

        if (!$user) {
            throw new BusinessException('登录用户不存在');
        }

        if ($user->status === 0) {
            throw new BusinessException('您的账号异常，请联系客服');
        }

        return $user;
    }

    /**
     * 验证内容安全
     * @param UsersModel $user
     * @param string $content
     * @throws \Exception
     */
    private function validateContentSecurity($user, $content)
    {
        if (empty($user->wechat_openid)) {
            // 如果没有微信openid，跳过微信安全检查
            return;
        }

        try {
            $wechatService = new WeChatMnpService();
            $checkResult = $wechatService->msgSecCheck($user->wechat_openid, $content);

            if (!$checkResult) {
                throw new \Exception('内容包含敏感文字，请修改后重试');
            }
        } catch (\Exception $e) {

            // 如果是我们自定义的敏感内容异常，直接抛出
            if (str_contains($e->getMessage(), '内容包含敏感文字')) {
                throw $e;
            }
            
            // 其他异常（如服务不可用），抛出统一的错误信息
            throw new \Exception('内容安全检查服务暂时不可用，请稍后重试');
        }
    }

    /**
     * 创建帖子
     * @param array $params
     * @param string $userId
     * @return PostModel
     * @throws \Exception
     */
    private function createPost($params, $userId)
    {
        $postData = [
            'user_id' => $userId,
            'topic_id' => $params['topic_id'],
            'class_id' => $params['class_id'],
            'content' => $params['content'],
            'media' => $params['media']
        ];

        if (!empty($params['title'])) {
            $postData['title'] = $params['title'];
        }

        if (!empty($params['discuss_id'])) {
            $postData['discuss_id'] = $params['discuss_id'];
        }

        if (!empty($params['topic_class_id'])) {
            $postData['topic_class_id'] = $params['topic_class_id'];
        }

        $post = PostModel::create($postData);

        if (!$post || !$post->id) {
            throw new \Exception('帖子创建失败，请重试');
        }

        return $post;
    }

    /**
     * 更新帖子相关统计数据
     * @param PostModel $post
     * @param UsersModel $user
     */
    private function updatePostStatistics($post, $user)
    {
        // 更新用户发帖数
        $user->increment('post_num');

        // 更新圈子帖子数
        TopicModel::where('id', $post->topic_id)->increment('post_num');

        // 更新话题帖子数（如果存在）
        if (!empty($post->discuss_id)) {
            DiscussModel::where('id', $post->discuss_id)->increment('post_num');
        }
    }

    /**
     * [帖子详情]
     * @return [json]
     */
    public function detail()
    {

        $id = input("id");
        $userId = $this->getUserId();

        PostModel::where('id', $id)->increment('see_num', rand(1, 20));
        $post = PostModel::where('id', $id)->with(["user", "topic"])->first();

        if (!$post) {
            return $this->fail('帖子不存在');
        }

        $post["comment_count"] = PostCommentModel::where('post_id', $id)->count();

        $post["is_follow"] = false;
        $post["is_thumb"] = false;

        if (!empty($userId)) {
            //是否已关注帖子作者
            $isFollow = \app\model\FollowModel::where('user_id', $userId)->where('follow_uid', $post['user_id'])->exists();
            if ($isFollow) {
                $post["is_follow"] = true;
            }

            //是否已点赞帖子
            $isThumb = PostLikeModel::where('user_id', $userId)->where('post_id', $id)->exists();
            if ($isThumb) {
                $post["is_thumb"] = true;
            }

            //是否已收藏帖子
            $isCollect = PostCollectionModel::where('user_id', $userId)->where('post_id', $id)->exists();
            if ($isCollect) {
                $post["is_collect"] = true;
            }
        }

        return $this->success($post->toArray());
    }

    //当前登录用户加入圈子的动态列表
    public function postListByjoinTopic()
    {
        $userId = $this->getUserId();
        $topicIds = \app\model\UserTopicModel::where('user_id', $userId)
            ->pluck('topic_id')
            ->toArray();

        $postList = PostModel::whereIn('topic_id', $topicIds)
            ->with(['user', 'topic'])
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return $this->dataByPage($postList);
    }

    //当前登录用户发布的帖子
    public function releaseList()
    {
        $userId = $this->getUserId();
        $list = PostModel::where('user_id', $userId)
            ->with(['user', 'topic'])
            ->orderBy('created_at', 'desc')
            ->paginate(10);
        return $this->dataByPage($list);
    }

    //用户点赞的帖子
    public function thumbList()
    {
        $userId = $this->getUserId();
        $postIds = PostLikeModel::where('user_id', $userId)->pluck('post_id')->toArray();

        $where[] = ["id", "in", $postIds];
        $paginate = PostModel::where($where)->paginate(10);
        return $this->dataByPage($paginate);
    }

    //用户收藏的帖子
    public function collectList()
    {
        $userId = $this->getUserId();
        $postIds = PostCollectionModel::where('user_id', $userId)->pluck('post_id')->toArray();

        $where[] = ["id", "in", $postIds];
        $list = PostModel::getList($where);
        return $this->dataByPage($list);
    }

    //搜索帖子
    public function search()
    {
        $keyword = input("keyword");
        $where[] = ["content", "like", "%$keyword%"];
        $paginate = PostModel::where($where)->paginate();
        return $this->dataByPage($paginate);
    }

    //删除帖子
    public function del()
    {
        $id = input("id");
        $userId = $this->getUserId();
        $postInfo = PostModel::where("id", $id)->first();
        $res = PostModel::destroy($id);
        if ($res) {
            TopicModel::where('id', $postInfo["topic_id"])->decrement('post_num');

            //是否当前登录用户自己的帖子
            if ($userId == $postInfo["user_id"]) {
                UsersModel::where('id', $userId)->decrement('post_num');
            } else {
                //通知用户帖子被删除

            }

            return $this->success("删除成功");
        }

        return $this->fail("删除失败");
    }

    //点赞帖子
    public function thumbAdd()
    {
        $userId = $this->getUserId();
        $postId = input("id");
        $toUserId = input("user_id");

        $exists = PostLikeModel::where('user_id', $userId)->where('post_id', $postId)->exists();
        if ($exists) {
            return $this->fail("请勿重复点赞");
        }

        $res = PostLikeModel::create([
            'user_id' => $userId,
            'post_id' => $postId
        ]);

        if ($res) {
            PostModel::where('id', $postId)->increment('thumb_num');
            Message::send($userId, $toUserId, $postId, 1, "点赞了您的贴子");

            return $this->success("点赞成功");
        }
        return $this->fail("收藏失败");
    }

    //取消点赞
    public function thumbCancel()
    {
        $userId = $this->getUserId();
        $postId = input("id");
        $where["user_id"] = $userId;
        $where["post_id"] = $postId;
        $res = PostLikeModel::where('user_id', $userId)->where('post_id', $postId)->delete();

        if ($res) {
            PostModel::where('id', $postId)->decrement('thumb_num');
            return $this->success("已取消点赞");
        }
        return $this->fail("取消点赞失败");
    }

    //收藏帖子
    public function collectAdd()
    {
        $userId = $this->getUserId();
        $postId = input("id");
        $toUserId = input("user_id");

        $data["user_id"] = $userId;
        $data["post_id"] = $postId;

        $exists = PostCollectionModel::where('user_id', $userId)->where('post_id', $postId)->exists();
        if ($exists) {
            return $this->fail("请勿重复收藏");
        }

        $res = PostCollectionModel::create([
            'user_id' => $userId,
            'post_id' => $postId
        ]);

        if ($res) {
            PostModel::where('id', $postId)->increment('collect_num');
            Message::send($userId, $toUserId, $postId, 3, "收藏了您的贴子");

            return $this->success("收藏成功");
        }
        return $this->fail("点赞失败");
    }

    //取消收藏
    public function collectCancel()
    {
        $userId = $this->getUserId();
        $postId = input("id");
        $where["user_id"] = $userId;
        $where["post_id"] = $postId;
        $res = PostCollectionModel::where('user_id', $userId)->where('post_id', $postId)->delete();

        if ($res) {
            PostModel::where('id', $postId)->decrement('collect_num');
            return $this->success("已取消收藏");
        }
        return $this->fail("取消收藏失败");
    }


//    微信检测帖子文本安全
    public function msgSecCheck()
    {
        $userId = $this->getUserId();
        $openid = UsersModel::where("id", $userId)->value('wechat_openid');

        $contentTxt = input("content");

        $checkTxt = (new W())->msgSecCheck($openid, $contentTxt);

        return $this->success($checkTxt->toArray());

    }

    //圈子内置顶帖子
    public function setTop()
    {
        $data = request()->all();
        $data['create_time'] = time();

        $res = \app\model\TopicTopModel::create($data);
        if ($res) {
            return $this->success("置顶成功");
        }

        return $this->fail("置顶失败");
    }


    //圈子内帖子取消置顶
    public function topPostDel()
    {
        $data = request()->all();
        $res = TopicTopModel::where($data)->delete();
        if ($res) {
            return $this->success();
        }

        return $this->fail();
    }

    public function checkPostImg()
    {
        $userId = $this->getUserId();
        $user = UsersModel::where("id", $userId)->first();

        $postId = input("post_id");

        $imgList = PostModel::where("id", $postId)->value("media");

        foreach ($imgList as $imgSrc) {
            $imgSrc = FileService::getFileUrl($imgSrc);
            $checkInfoJSon = (new WeChatMnpService())->mediaCheckAsync($user["wechat_mp_openid"], $imgSrc);
            $checkInfo = json_decode($checkInfoJSon);
            MediaCheckModel::create([
                'trace_id' => $checkInfo->trace_id,
                'post_id' => $postId,
                'media_src' => $imgSrc
            ]);
        }

        return $this->success();
    }

    /**
     * 生成帖子二维码
     * @return \support\Response
     */
    public function qrCode()
    {
        try {
            // 参数验证
            $params = request()->all();
            $rules = [
                'post_id' => 'required'
            ];
            $messages = [
                'post_id.required' => '帖子ID不能为空'
            ];
            
            $validator = validator($params, $rules, $messages);
            if ($validator->fails()) {
                return $this->fail($validator->errors()->first());
            }
            
            $postId = $params['post_id'];
            
            // 检查帖子是否存在且状态正常
            $post = PostModel::where('id', $postId)->first();
            if (!$post) {
                return $this->fail('帖子不存在或已被删除');
            }
            
            // 检查二维码是否已存在
            $qrcodePath = public_path(). DIRECTORY_SEPARATOR . 'qrcode' . DIRECTORY_SEPARATOR . 'post';
            $filename = $qrcodePath . DIRECTORY_SEPARATOR . $postId . '.png';
            
            // 如果二维码已存在且文件有效，直接返回
            if (file_exists($filename) && filesize($filename) > 0) {
                $data = [
                    'url' => '//' . request()->host() . "/qrcode/post/{$postId}.png"
                ];
                return $this->success($data, '获取成功');
            }
            
            // 创建目录（递归创建）
            if (!is_dir($qrcodePath)) {
                if (!mkdir($qrcodePath, 0755, true)) {
                    return $this->fail('创建二维码目录失败');
                }
            }
            
            // 生成二维码
            $weChatService = new WeChatMnpService();
            $response = $weChatService->getQrCode('pages/post/detail', $postId);
            
            if (!$response) {
                return $this->fail('生成二维码失败');
            }

            $data = [
                'url' => '//' . request()->host() . "/qrcode/post/{$postId}.png"
            ];
            
            return $this->success($data, '获取成功');
            
        } catch (\Exception $e) {
            return $this->fail('生成二维码失败：' . $e->getMessage());
        }
    }

    //获取待机器人推送帖子列表
    public function botPostList()
    {
        $topicId = input("topic_id");

        if (empty($topicId)) {
            return $this->fail("参数:topic_id为空");
        }

        $where[] = ["is_bot", "=", 0];
        $where[] = ["topic_id", "=", $topicId];

        $list = PostModel::where($where)->select(['id', 'content', 'class_id'])->limit(5)->get()->toArray();

        $postList = [];
        foreach ($list as $item) {
            PostModel::where("id", $item["id"])->update(["is_bot" => 1]);

            $shortLink = (new WeChatMnpService())->getShortLink('pages/post/detail?id=' . $item['id']);
            $shortLink = json_decode($shortLink);
            $postList[] = [
                "content" => $item["content"],
                "wx_link" => $shortLink->link,
                "qq_link" => 'https://q.meoyun.com/p/' . $item["id"],
                "class_name" => TopicClassModel::where("id", $item["class_id"])->value('name')
            ];

        }

        return $this->success($postList);
    }
}